/*
 *@Description: 新笔趣阁  http://www.xbiquge.la/
 *@Author:  lupan
 *@Date: 2019-06-23 10:20:00
*/
const {BookInfo, BookChapter} = require('../../db/model/index')
const url = 'https://www.biquge5.com/'

/*
 *@name: 采集小说章节
 *@param:{type} 
 *@description:
 *@return:
 *@author: panlua
 *@date: 2019-06-24 16:51:48
*/
const gatBookChapter = (page, bookInfo)=> {
  return new Promise(resolve => {
    (async ()=> {
      await page.waitFor(2000)
      await page.type('#searchkey', bookInfo.title)
      await page.click('#sss')
      await page.waitFor(2000)
      await LOG.success(`搜索${bookInfo.title}成功`)
      // 获取小说
      try {
        await page.click('#webbegin .list-group .list-group-item:nth-child(1) .row a')
        await page.waitFor(2000)
        await LOG.success(`${bookInfo.title}章节打开成功`)
        const bookChapterData = await page.$$eval('#list > ul > li > a', els => Array.prototype.slice.call(els).map(el => {
          return {
            gatUrl: el.href,
            name: el.innerText
          }
        }))
        await bookChapterData.map(item => {
          item.bookInfoId = bookInfo._id
        })
        for (let i = 0; i < bookChapterData.length; i++) {
          await bookContent(page, bookChapterData[i], bookInfo.title)
          if (i === bookChapterData.length - 1) {
            await resolve()
          }
        }
      } catch (err) {
        await page.waitFor(30000)
        await page.goto(url)
        await resolve()
      }
    })()
  })
}

const bookContent = (page, bookChapterInfo, bookTitle) => {
  return new Promise(resolve => {
    (async () => {
      await page.goto(bookChapterInfo.gatUrl)
      await LOG.success(`${bookTitle}___${bookChapterInfo.name}打开成功`)
      const bookContent = await page.$eval('#content', el => el.innerText)
      await LOG.success(`${bookTitle}___${bookChapterInfo.name}内容采集成功`)
      const BookChapterDB = await BookChapter.create(Object.assign(bookChapterInfo, {
        content: bookContent
      }))
      await LOG.success(`${bookTitle}___${bookChapterInfo.name}内容写入成功`)
      await resolve()
    })()
  })
}

const xbqg = {
  gat: async(page) => {
    await page.goto(url)
    await LOG.success('笔趣阁首页打开成功')
    const bookData = await BookInfo.find({}, {'_id': 1, 'title': 1, 'author': 1})
    await LOG.success(`所有书籍获取成功，一共${bookData.length}本`)
    for (let i = 0; i < bookData.length; i++) {
      await gatBookChapter(page, bookData[i])
    }
  }
}

export default xbqg